package com.bdqn.business.academic.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bdqn.business.academic.dao.AskMapper;
import com.bdqn.business.academic.dao.ChapterMapper;
import com.bdqn.entity.academic.Ask;
import com.bdqn.entity.academic.Chapter;
import com.bdqn.entity.academic.Single;
import com.bdqn.response.PageResult;
import com.bdqn.response.Result;
import com.bdqn.response.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

@Service
@Transactional
public class AskService {

    @Autowired
    private AskMapper askMapper;

    @Autowired
    private ChapterMapper chapterMapper;

    public Result getList(Map<String, Object> map) {
        Integer page = Integer.parseInt(map.get("page").toString());
        Integer size = Integer.parseInt(map.get("size").toString());

        QueryWrapper<Ask> queryWrapper = new QueryWrapper<>();

        queryWrapper.orderByDesc("create_time");

        IPage<Ask> singleIPage = new Page<>(page,size);

        IPage<Ask> result = askMapper.selectPage(singleIPage, queryWrapper);

        PageResult<Ask> pageResult = new PageResult<>(result.getTotal(),result.getRecords());

        return new Result(ResultCode.SUCCESS,pageResult);
    }

    @CachePut(cacheNames = "ask",key = "#ask.id")
    public Result saveAsk(Ask ask) {
        Chapter chapter = chapterMapper.selectById(ask.getChapterId());
        ask.setChapterName(chapter.getName());
        ask.setStatus("1"); //启用
        ask.setCreateTime(new Date());


        if(ask.getAskContent().contains("<img")){
            ask.setAskContent(ask.getAskContent().replaceAll("<img","<img width='300px' height='300px' "));
        }

        askMapper.insert(ask);
        return new Result(ResultCode.SUCCESS,ask);
    }
}
